package com.xindaoapp.happypet.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.MyOrderAdapter;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.MyOrder;
import com.xindaoapp.happypet.bean.MyOrderList;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.ProgressHUD;
import com.xindaoapp.happypet.utils.xdConfig;

/**
 * 我的订单列表
 * 
 * @author chenghao
 */
public class MyOrderListActivity extends BaseLoadAnimationAcitivity {
    private static final String TAG = "MyOrderListActivity";
    // private RelativeLayout no_data;
    private ImageButton back;
    private TextView title;
    private int flag;

    private PullToRefreshListView listView;
    private MyOrderAdapter mAdapter;

    private static Context mContext;

    private MyOrderListBroadCast boradCast;
    private int location;
    // private static boolean isFirstLoading = true;
    private static ProgressHUD progressHUD;
    private boolean submitOrder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_myorder_list);
        super.onCreate(savedInstanceState);
        flag = getIntent().getIntExtra("flag", -1);
        submitOrder = getIntent().getBooleanExtra("submitOrder", false);
        mContext = MyOrderListActivity.this;

        initView();
        initData();
        getInitData();

        boradCast = new MyOrderListBroadCast();
        registerReceiver(boradCast, new IntentFilter(Constants.ORDER_DETAIL));
    }

    @Override
    protected void onResume() {
        if (mAdapter != null) {
            initData();
            getInitData();
        }
        super.onResume();
    }

    private void initView() {
        // no_data = (RelativeLayout) findViewById(R.id.no_data);
        back = (ImageButton) findViewById(R.id.cancel);
        title = (TextView) findViewById(R.id.check_club);
        listView = (PullToRefreshListView) findViewById(R.id.listview);
        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getInitData();
            }
        });
    }

    // 订单列表返回按钮
    private void initData() {
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (submitOrder) {
                    // 跳转到首页
                    Intent i =
                            new Intent(MyOrderListActivity.this,
                                    com.xindaoapp.happypet.ui.MainActivity.class);
                    i.putExtra(Constants.KEY_SHOP_HOME, 2);
                    startActivity(i);
                }
                finish();

            }
        });
        switch (flag) {
            case 1:
                title.setText("待付款订单");
                break;
            case 2:
                title.setText("待发货订单");
                break;
            case 3:
                title.setText("待收货订单");
                break;
            case 4:
                title.setText("已完成订单");
                break;
            default:
                break;
        }
    }

    private void getInitData() {
        getData(mContext, flag + "", 1, xdConfig.PAGE_SIZE, new ILoadNextPageData<MyOrder>() {

            @Override
            public void loadNextPageData(List<MyOrder> t) {
                if (null != t) {
                    mAdapter =
                            new MyOrderAdapter(mContext, t, xdConfig.PAGE_SIZE,
                                    R.layout.activity_myorder_list_item, R.layout.item_loading,
                                    flag + "");
                    listView.setAdapter(mAdapter);
                    if (mAdapter.getResult().size() > 0) {
                        // no_data.setVisibility(View.GONE);
                        onDataArrived(true);
                    } else {
                        onDataArrivedEmpty();
                        // no_data.setVisibility(View.VISIBLE);
                    }
                    listView.setPullLabel("加载成功");
                } else {
                    listView.setPullLabel("加载失败");
                    onDataArrived(false);
                    // CRToast.show(mContext, "获取数据失败");
                }
                listView.onRefreshComplete();
            }
        });
    }

    public static void getData(final Context mContext, String flag, final int pageNumber, int size,
            final ILoadNextPageData<MyOrder> iRequest) {
        RequestParams params = new RequestParams();
        params.put("type", CommonUtil.decode("0"));
        params.put("page", CommonUtil.decode(String.valueOf(pageNumber)));
        params.put("pageSize", CommonUtil.decode(String.valueOf(size)));
        params.put("userID", CommonUtil.decode(UserState.getUserUid()));
        params.add("version", "1.0");
        AddClient.get(Address.MY_ORDER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                org.json.JSONObject obj;
                String data = null;
                try {
                    obj = new org.json.JSONObject(content);
                    if ("暂无数据！".equals(obj.getString("msg"))) {
                        iRequest.loadNextPageData(new ArrayList<MyOrder>());
                        return;
                    }
                    data = obj.getString("data");
                    if (TextUtils.isEmpty(data)) {
                        // Toast.makeText(mContext, "获取数据失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    MyOrderList entity = JSON.parseObject(data, MyOrderList.class);
                    Log.i(TAG, data);
                    // 判断返回数据是否正确
                    if (null != entity) {
                        iRequest.loadNextPageData(entity.info);
                    } else {
                        iRequest.loadNextPageData(null);
                    }
                } catch (JSONException e) {
                    iRequest.loadNextPageData(null);
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable arg0, String arg1) {

                super.onFailure(arg0, arg1);
                iRequest.loadNextPageData(null);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(boradCast);
    }

    private class MyOrderListBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            location = mAdapter.getClickChild();
            mAdapter.getResult().remove(location);
            mAdapter.notifyDataSetChanged();
        }
    }
}
